﻿
package extremefx.drawing {
	import extremefx.events.EventHandler;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.utils.ByteArray;	

	/**
	 * @author Marcelo Volmaro
	 */
	public final class ByteToBitmap {
		private var _loader:Loader;
		private var _bmp:Bitmap;
		private var _eOnLoad:EventHandler = new EventHandler(this);
		
		/**
		 * Loads and decode a byte array into a bitmap
		 * @param pB the byte array that holds the encoded bitmap
		 */
		public function ByteToBitmap(pB:ByteArray) {
			var l:Loader = _loader = new Loader();
			l.loadBytes(pB);
			l.contentLoaderInfo.addEventListener(Event.COMPLETE, _onComplete, false, 0, true);
		}
		
		/**
		 * Event. Fires when the decoding has been completed
		 */
		public function get onLoad():EventHandler {
			return _eOnLoad;
		}
		
		private function _onComplete(pE:Event):void{
			_bmp = Bitmap(_loader.content);
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, _onComplete);
			_loader = null;
			_eOnLoad.fire();
		}
		
		/**
		 * Gets the decoded bitmap. You must get the bitmap after the <code>onLoad</code> event has been fired.
		 * @return the decoded bitmap.
		 */
		public function get bitmap():Bitmap {
			return _bmp;
		}
	}
}
